package com.yxkj.syh.app.huarong.activities.home.return_cars;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.syh.app.basic.App;
import com.syh.app.basic.base.BaseResponse;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.yxkj.syh.app.huarong.bean.AliCityResponse;
import com.yxkj.syh.app.huarong.bean.AreaPlus;
import com.yxkj.syh.app.huarong.bean.ReturnCar;
import com.yxkj.syh.app.huarong.bean.ReturnCarResponse;
import com.yxkj.syh.app.huarong.data_center.model.AliCityModel;
import com.yxkj.syh.app.huarong.data_center.model.ReportModel;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * 创建者：SYH
 * 时间：2020/6/3 17:30
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class ReturnCarVM extends BaseViewModel<ActivityEvent> {

    public ReturnCarVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofFrom = new ObservableField<>();
    public ObservableField<String> ofTo = new ObservableField<>();
    public ObservableField<String> ofCreatTime = new ObservableField<>();
    public ObservableField<String> ofCarID = new ObservableField<>();

    public MutableLiveData<ReturnCar> mldReturnCar = new MutableLiveData<>();

    public void returnCarInfo(long id){
        ReportModel.getReportModel().returnCarInfo(id,mLifecycleProvider.bindToLifecycle(), new ApiObserver<ReturnCarResponse>() {
            @Override
            public void onSuccess(ReturnCarResponse carResponse) {
                ReturnCar returnCar = carResponse.getData();
                ofFrom.set(returnCar.getStartArea());
                ofTo.set(returnCar.getEndArea());
                ofCreatTime.set(returnCar.getCreateTime());
                ofCarID.set(returnCar.getCarNo());
                mldReturnCar.setValue(returnCar);

            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 预约
     */
    public void appointment(long id,String remark){

        Map<String,Object> pMap = new HashMap<>();
        pMap.put("id",id);
        pMap.put("remark",remark);

        showLoading("appointment");
        ReportModel.getReportModel().appointment(pMap,mLifecycleProvider.bindToLifecycle(), new ApiObserver<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                hideLoading("appointment");
                Tooast.success(response.getMessage());
                EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_USER));
                finish();
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("appointment");
                Tooast.warning(msg);
            }
        });
    }















    /**
     * 地址选择器的数据源提供者
     */
    public AddressProvider addressProvider = new AddressProvider() {
        @Override
        public void provideProvinces(AddressReceiver<Province> addressReceiver) {
            addressReceiver.send(getProvince());
        }

        @Override
        public void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver) {
            cities(provinceId, addressReceiver);
        }

        @Override
        public void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver) {
            counties(cityId, addressReceiver);
        }

        @Override
        public void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver) {
            addressReceiver.send(null);
        }
    };

    /**
     * 查市
     */
    public void cities(int provinceId, AddressProvider.AddressReceiver<City> addressReceiver) {

        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(1, provinceId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel2Pluses.clear();
                    areaLevel2Pluses.addAll(response.getShowapi_res_body().getData());
                    cities.clear();
                    for (int i = 0; i < areaLevel2Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel2Pluses.get(i);
                        City city = new City();
                        city.id = i + 1;
                        city.name = areaPlus.getAreaName();
                        city.province_id = provinceId;
                        areaPlus.setCity(city);
                        cities.add(city);
                    }
                    addressReceiver.send(cities);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 查区县
     */
    public void counties(int cityId, AddressProvider.AddressReceiver<County> addressReceiver) {
        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(2, cityId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel3Pluses.clear();
                    areaLevel3Pluses.addAll(response.getShowapi_res_body().getData());
                    counties.clear();
                    for (int i = 0; i < areaLevel3Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel3Pluses.get(i);
                        County county = new County();
                        county.id = i + 1;
                        county.name = areaPlus.getAreaName();
                        county.city_id = cityId;
                        areaPlus.setCounty(county);
                        counties.add(county);
                    }
                    addressReceiver.send(counties);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }


    private List<AreaPlus> areaLevel1Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel2Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel3Pluses = new ArrayList<>();
    private List<Province> provinces = new ArrayList<>();
    private List<City> cities = new ArrayList<>();
    private List<County> counties = new ArrayList<>();

    /**
     * 读省
     *
     * @return
     */
    private List<Province> getProvince() {
        if (provinces.size() == 0) {
            try {
                // 获取json文件数据源,流的方式呈现
                InputStream inputStream = App.getApplication().getAssets().open("province.json");
                // 读取JSON文件流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp = "";
                String jsonSource = "";
                //一行一行的读取
                while ((temp = bufferedReader.readLine()) != null) {
                    jsonSource += temp;
                }
                //关闭
                bufferedReader.close();
                inputStream.close();

                JSONObject jsonObject = new JSONObject(jsonSource);
                List<AreaPlus> areaPluses = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<AreaPlus>>() {
                }.getType());

                areaLevel1Pluses.clear();
                areaLevel1Pluses.addAll(areaPluses);

                for (int i = 0; i < areaLevel1Pluses.size(); i++) {
                    AreaPlus provincePlus = areaLevel1Pluses.get(i);
                    Province province = new Province();
                    province.name = provincePlus.getAreaName();
                    province.id = i + 1;
                    provinces.add(province);
                    provincePlus.setProvince(province);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return provinces;
    }


    /**
     * 查 AreaPlusId
     *
     * @param subId 子类 id
     */
    public long getAreaPlusId(int level, int subId) {
        long id = 0l;

        if (level == 1) {
            for (AreaPlus areaPlus : areaLevel1Pluses) {
                if (areaPlus.getProvince().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 2) {
            for (AreaPlus areaPlus : areaLevel2Pluses) {
                if (areaPlus.getCity().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 3) {
            for (AreaPlus areaPlus : areaLevel3Pluses) {
                if (areaPlus.getCounty().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        }


        return id;
    }
}
